#!/bin/sh

### BEGIN INIT INFO
# Provides:          GoTasks
# Required-Start:    $remote_fs $network
# Required-Stop:     $remote_fs $network
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: starts GoTasks
# Description:       Starts GoTasks
### END INIT INFO

# 显示名称、描述文字
NAME=GoTasks
DESC="tasks service"

# 日志输出目录、级别
LOG_DIR=/var/log/go_tasks
LOG_LEVEL=1

# Tasks URL
TASKS=""

# 更新任务周期
CYCLE=43200

# 可执行文件所在
DAEMON=

# 执行命令的参数
DAEMON_ARGS="-tasks=${TASKS} -cycle=${CYCLE} -log-dir=${LOG_DIR} -log-level=${LOG_LEVEL} -console=false"

# pid文件
PIDFILE=/var/run/go_tasks.pid
TIMEOUT=30

# 测试命令
TEST="${DAEMON} ${DAEMON_ARGS} --test=1"

. /lib/lsb/init-functions

# 前置检查

if [ -z "${DAEMON}" ]; then
	echo "Please specify the daemon file!"
	exit 1
fi

if [ ! -f "${DAEMON}" ]; then
	echo "The file ${DAEMON} does not exist!"
	exit 1
fi

if [ ! -x "${DAEMON}" ]; then
	echo "The file ${DAEMON} cannot be executed, please use chmod +x ${DAEMON}!"
	exit 1
fi

if [ ! -d "${LOG_DIR}" ]; then
	echo "The log dir does not exist, please mkdir ${LOG_DIR}"
	exit 1
fi

TEST_ERR=$(${TEST})

if [ -n "${TEST_ERR}" ]; then
	echo "${TEST_ERR}"
	exit 1
fi


# 检查进程是否已经存在
# 0 不存在进程
# 1 进程已经存在
check_proc() {
	[ ! -f "${PIDFILE}" ] && return 0
	if ps -p $(cat $PIDFILE) > /dev/null 2>&1
	then
		return 1
	else
		return 0
	fi
}

show_proc() {
	if [ ! -f "${PIDFILE}" ]; then
		echo "Process file ${PIDFILE} does not exist!"
		return 0
	fi
	
	/bin/ps -p "$(cat $PIDFILE)"
	return 0
}

# 启动进程
# 0 成功启动
# 1 进程已经存在
# 2 进程启动失败
start_proc()
{
	check_proc
	case "$?" in
		0)
			start-stop-daemon \
				--start \
				--quiet --background \
				--pidfile ${PIDFILE} --make-pidfile \
				--exec ${DAEMON} -- ${DAEMON_ARGS} 2>/dev/null \
				|| return 2
			;;
		1)
			# 进程已经存在，没啥可做
			return 1
			;;
	esac
}

# 停止进程

stop_proc()
{
        # Return
        #   0 if daemon has been stopped
        #   1 if daemon was already stopped
        #   2 if daemon could not be stopped
        #   other if a failure occurred
        start-stop-daemon --stop --quiet --retry=QUIT/${TIMEOUT}/TERM/5/KILL/5 --pidfile ${PIDFILE} --name ${NAME}
        RETVAL="$?"
        [ "${RETVAL}" = 2 ] && return 2
        # Wait for children to finish too if this is a daemon that forks
        # and if the daemon is only ever run from this initscript.
        # If the above conditions are not satisfied then add some other code
        # that waits for the process to drop all resources that could be
        # needed by services started subsequently.  A last resort is to
        # sleep for some time.
        start-stop-daemon --stop --quiet --oknodo --retry=0/30/TERM/5/KILL/5 --exec ${DAEMON}
        [ "$?" = 2 ] && return 2
        # Many daemons don't delete their pidfiles when they exit.
        rm -f ${PIDFILE}
        return "${RETVAL}"
}

case "$1" in
    start)
        log_daemon_msg "Starting ${DESC}" "${NAME}"
		start_proc
		case "$?" in
            0) 
				log_end_msg 0  # 启动成功 		log_end_msg 0 是OK
				;;
            1) 
				log_end_msg 1  # 进程已经存在 	log_end_msg 1 是fail
				echo "The process ${DAEMON} is existing!"
				;;
			2) 
				log_end_msg 1  # 启动失败		log_end_msg 1 是fail
				echo "Unknown error!"
				;;
        esac
        ;;
    stop)
        log_daemon_msg "Stopping ${DESC}" "${NAME}"
        stop_proc
        case "$?" in
			0|1) log_end_msg 0 ;;
			2) log_end_msg 1 ;;
        esac
        ;;
    status)
        status_of_proc "${DAEMON}" "${NAME}" && exit 0 || exit $?
        ;;
    restart)
        log_daemon_msg "Restarting ${DESC}" "${NAME}"
        stop_proc
        case "$?" in
          0|1)
				start_proc
				case "$?" in
					0) 
						log_end_msg 0  # 启动成功 		log_end_msg 0 是OK
						;;
					1) 
						log_end_msg 1  # 进程已经存在 	log_end_msg 1 是fail
						echo "The process ${DAEMON} is existing!"
						;;
					2) 
						log_end_msg 1  # 启动失败		log_end_msg 1 是fail
						echo "Unknown error!"
						;;
				esac
                ;;
          *)
                # Failed to stop
                log_end_msg 1
                ;;
        esac
        ;;
	proc)
		show_proc
		;;
    *)
        echo "Usage: /etc.init.d/go_tasks {start|stop|status|restart|proc}"
        exit 1
        ;;
esac

:
